package com.chat;

import com.chat.mapper.*;
import com.chat.pojo.Group;
import com.chat.pojo.GroupMessage;
import com.chat.pojo.Message;
import com.chat.pojo.UserInfo;
import com.chat.util.DbUtil;
import org.apache.ibatis.session.SqlSession;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;


public class ChatFrame extends JFrame {

    private JTextArea chatArea;
    private JTextField inputField;
    private JList<String> friendList;
    private DefaultListModel<String> listModel;
    private String currentFriend = "";
    // 用户信息
    private UserInfo userInfo;
   private JPanel infoPanel;
   private JLabel nameLabel;
   private JLabel accountLabel;
   private JLabel signLabel;
    // JLabel avatarLabel;

    //通信
    private Socket chatSocket;
    private BufferedReader in;
    private PrintWriter out;
    private int currentFriendUserId;
    private UserInfo currentFriendUserInfo;
    // 好友列表数据
    private List<UserInfo> friends;
    private DefaultListModel<String> groupListModel;
    private int currentGroupId;




    // public ChatFrame() {
    public ChatFrame(UserInfo userInfo) {
        this.userInfo = userInfo;

        System.out.println("chatF:" + userInfo);

        // 初始化 friends 防止空指针
        this.friends = new ArrayList<>();
        setTitle("QQ 多人聊天界面");
        setSize(1000, 600);
        setLocationRelativeTo(null); // 居中显示
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        // 初始化UI
        initializeUI();
        loadFriendsFromDatabase();
        connectToChatServer();

        // // 添加定时刷新好友列表的任务，每5秒执行一次
        // Timer refreshTimer = new Timer(5000, e -> loadFriendsFromDatabase());
        // refreshTimer.start();

    }

    // 修改loadFriendsFromDatabase方法
    private void loadFriendsFromDatabase() {
        try (SqlSession session = DbUtil.getSession()) {
            FriendShipMapper friendshipMapper = session.getMapper(FriendShipMapper.class);
            System.out.println( userInfo.getUserId());

            friends = friendshipMapper.getFriendsByUserId(userInfo.getUserId());
            System.out.println("Found " + friends.size() + " friends");

            // 确保在EDT中更新UI
            SwingUtilities.invokeLater(() -> {
                listModel.clear();
                for (UserInfo friend : friends) {
                    String name = friend.getAccountname() != null ? friend.getAccountname() : "未知用户";
                    listModel.addElement(name);
                    System.out.println("Added friend: " + name);
                }
                // 强制刷新
                friendList.revalidate();
                friendList.repaint();
            });
        } catch (Exception e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(this,
                    "加载好友列表失败：" + e.getMessage(),
                    "错误", JOptionPane.ERROR_MESSAGE);
        }
    }


    private void initializeUI() {
        // 主布局：左右结构
        JSplitPane mainSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
        mainSplitPane.setDividerLocation(200); // 设置分隔线位置
        mainSplitPane.setOneTouchExpandable(true);
        // 左侧面板 - 个人信息展示区域
        // getUsername
        infoPanel = new JPanel(new GridLayout(4, 1));
        nameLabel = new JLabel("昵称: " + userInfo.getAccountname());
        accountLabel = new JLabel("账号: " + userInfo.getUsername());
        signLabel = new JLabel("个性标签: " + userInfo.getPersonSign());
        // avatarLabel = new JLabel("头像: " + userInfo.getAvatarUrl());

        infoPanel.add(nameLabel);
        infoPanel.add(accountLabel);
        infoPanel.add(signLabel);
        // infoPanel.add(avatarLabel);
        JButton editButton = new JButton("编辑");
        editButton.addActionListener(e -> {
            new EditProfileDialog(this, userInfo).setVisible(true);
        });
        infoPanel.add(editButton);


        // 左侧面板 - 好友列表
        listModel = new DefaultListModel<>();
        friendList = new JList<>(listModel);
        friendList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        // 设置每个好友的列表的高度
        friendList.setFixedCellHeight(40);
        friendList.setFont(new Font("宋体", Font.PLAIN, 15));


// 按钮部分
        JButton addButton = new JButton("添加好友");
        JButton removeButton = new JButton("删除好友");
        JPanel buttonPanel = new JPanel(new FlowLayout());
        buttonPanel.add(addButton);
        buttonPanel.add(removeButton);


        // 好友列表和群聊列表按钮
        JButton friendListButton = new JButton("好友列表");
        JButton groupListButton = new JButton("群聊列表");
        buttonPanel.add(friendListButton);
        buttonPanel.add(groupListButton);
        // 群聊列表
        // 群聊列表
        groupListModel = new DefaultListModel<>();
        JList<String> groupList = new JList<>(groupListModel);
        groupList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        groupList.setFixedCellHeight(40);
        groupList.setFont(new Font("宋体", Font.PLAIN, 15));
        // 群聊列表选择监听器
        groupList.addListSelectionListener(e -> {
            if (!e.getValueIsAdjusting()) {
                String selectedGroupName = groupList.getSelectedValue();
                chatArea.setText("【正在群聊：" + selectedGroupName + "】\n");
                System.out.println("当前群聊：" + selectedGroupName);

                // 根据群组名称获取群组ID并设置 currentGroupId
                currentGroupId = getGroupIdByName(selectedGroupName);

                loadGroupChatHistory(selectedGroupName);
            }
        });

        JScrollPane groupScrollPane = new JScrollPane(groupList);
        groupScrollPane.setBorder(BorderFactory.createTitledBorder("群聊列表"));
        loadGroupsFromDatabase();


        // friendList = new JList<>(listModel);
        friendList.addListSelectionListener(e -> {
            if (!e.getValueIsAdjusting()) {
                currentFriend = friendList.getSelectedValue();
                chatArea.setText("【正在和 " + currentFriend + " 聊天】\n");

                // 获取当前选中的好友对象
                String selectedAccountName = friendList.getSelectedValue();
                System.out.println("当前好友：" + selectedAccountName);
                for (UserInfo friend : friends) {
                    if (friend.getAccountname().equals(selectedAccountName)) {
                        currentFriendUserInfo = friend;
                        System.out.println("当前好友对象：" + currentFriendUserInfo);
                        currentFriendUserId = friend.getUserId();
                        System.out.println("当前好友ID：" + currentFriendUserId);
                        loadChatHistory(currentFriendUserId);
                        break;
                    }
                }
            }
        });
        JScrollPane friendScrollPane = new JScrollPane(friendList);
        friendScrollPane.setBorder(BorderFactory.createTitledBorder("好友列表"));
        mainSplitPane.setLeftComponent(friendScrollPane);

        // 创建一个卡片布局的面板来切换好友列表和群聊列表
        JPanel listCardPanel = new JPanel(new CardLayout());
        listCardPanel.add(friendScrollPane, "friends");
        listCardPanel.add(groupScrollPane, "groups");
        // 按钮切换事件
        friendListButton.addActionListener(e -> {
            CardLayout cardLayout = (CardLayout) listCardPanel.getLayout();
            cardLayout.show(listCardPanel, "friends");
        });

        groupListButton.addActionListener(e -> {
            CardLayout cardLayout = (CardLayout) listCardPanel.getLayout();
            cardLayout.show(listCardPanel, "groups");
        });

        // 添加好友功能
        addButton.addActionListener(e -> {
            String newName = JOptionPane.showInputDialog(ChatFrame.this,
                    "请输入好友名称：", "添加好友", JOptionPane.PLAIN_MESSAGE);
            System.out.println("新好友账号："+newName);

            if (newName != null && !newName.trim().isEmpty()) {
                SqlSession session = null;
                try {
                    session = DbUtil.getSession();
                    UserMapper userMapper = session.getMapper(UserMapper.class);
                    FriendShipMapper friendshipMapper = session.getMapper(FriendShipMapper.class);

                    // 1. 查找用户
                    UserInfo friend = userMapper.findUserByUsername(newName.trim());
                    System.out.println(newName.trim());//账号
                    System.out.println("添加好友" + friend);
                    System.out.println("--->" + userInfo + "--->" + friend);

                    if (friend == null) {
                        JOptionPane.showMessageDialog(ChatFrame.this,
                                "找不到该用户，请检查用户名是否正确！",
                                "错误", JOptionPane.ERROR_MESSAGE);
                        return;
                    }


                    System.out.println("检查好友" + userInfo.getUserId() + "  " + friend.getUserId());

                    // 2. 检查是否已是好友
                    boolean isAlreadyFriend = friendshipMapper.checkFriendRelationship(
                            userInfo.getUserId(),
                            friend.getUserId());
                    System.out.println(isAlreadyFriend);

                    if (isAlreadyFriend) {
                        JOptionPane.showMessageDialog(ChatFrame.this,
                                "你们已经是好友了！",
                                "提示", JOptionPane.INFORMATION_MESSAGE);
                        return;
                    }

                    System.out.println(" 新朋友网名 " + friend.getAccountname());

                    // 3. 添加双向好友关系
                    friendshipMapper.addFriend(userInfo.getUserId(), friend.getUserId());
                    friendshipMapper.addFriend(friend.getUserId(), userInfo.getUserId()); // 双向关系
                    System.out.println("--->" + userInfo.getUserId() + "--->" + friend.getUserId());
                    System.out.println(" 新朋友网名 " + friend.getAccountname());
                    System.out.println(friend.getAccountname());
                    listModel.addElement(friend.getAccountname());
                    session.commit();
                    System.out.println(friend.getAccountname());

                    JOptionPane.showMessageDialog(ChatFrame.this,
                            "添加好友成功！",
                            "提示", JOptionPane.INFORMATION_MESSAGE);

                } catch (Exception ex) {
                    if (session != null) {
                        session.rollback();
                    }
                    JOptionPane.showMessageDialog(ChatFrame.this,
                            "添加好友时发生错误：" + ex.getMessage(),
                            "错误", JOptionPane.ERROR_MESSAGE);
                    ex.printStackTrace();
                } finally {
                    if (session != null) {
                        session.close();
                    }
                }
            }
        });

// 删除好友功能
        removeButton.addActionListener(e -> {
            int selectedIndex = friendList.getSelectedIndex();
            if (selectedIndex == -1) {
                JOptionPane.showMessageDialog(ChatFrame.this, "请先选择一个好友！", "提示", JOptionPane.WARNING_MESSAGE);
                return;
            }

            String selectedFriendAccountName = friendList.getSelectedValue();

            // 弹出确认对话框
            int confirm = JOptionPane.showConfirmDialog(
                    ChatFrame.this,
                    "确定要删除好友 " + selectedFriendAccountName + " 吗？",
                    "删除确认",
                    JOptionPane.YES_NO_OPTION
            );

            if (confirm != JOptionPane.YES_OPTION) {
                return;
            }

            try (SqlSession session = DbUtil.getSession()) {
                FriendShipMapper friendshipMapper = session.getMapper(FriendShipMapper.class);
                MessageMapper messageMapper = session.getMapper(MessageMapper.class); // 新增：获取 MessageMapper

                // 获取当前选中好友的 UserInfo 对象
                UserInfo friendInfo = null;
                List<UserInfo> friends = friendshipMapper.getFriendsByUserId(userInfo.getUserId());
                for (UserInfo friend : friends) {
                    if (friend.getAccountname().equals(selectedFriendAccountName)) {
                        friendInfo = friend;
                        break;
                    }
                }

                if (friendInfo == null) {
                    JOptionPane.showMessageDialog(ChatFrame.this, "无法找到该好友的信息。", "错误", JOptionPane.ERROR_MESSAGE);
                    return;
                }

                // 删除聊天记录
                int friendId = friendInfo.getUserId();
                // 删除信息表中的聊天记录
                messageMapper.deleteMessagesBetweenUsers(userInfo.getUserId(), friendId); // 新增：删除聊天记录



                // 删除双向记录
                friendshipMapper.deleteFriend(userInfo.getUserId(), friendInfo.getUserId());
                friendshipMapper.deleteFriend(friendInfo.getUserId(), userInfo.getUserId());

                session.commit();

                // 更新 UI
                listModel.remove(selectedIndex);
                chatArea.setText("");
                currentFriend = "";

                JOptionPane.showMessageDialog(ChatFrame.this, "已成功删除好友：" + selectedFriendAccountName, "提示", JOptionPane.INFORMATION_MESSAGE);

            } catch (Exception ex) {
                JOptionPane.showMessageDialog(ChatFrame.this, "删除好友时发生错误：" + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
                ex.printStackTrace();
            }
        });


        JPanel leftPanel = new JPanel(new BorderLayout());
        leftPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); // 内边距

        // 个人信息面板美化
        infoPanel.setBackground(new Color(240, 240, 240));
        infoPanel.setBorder(BorderFactory.createTitledBorder("个人信息"));

        // 按钮美化
        addButton.setBackground(new Color(100, 180, 255));
        removeButton.setBackground(new Color(255, 100, 100));

        // 好友列表滚动面板美化
        friendScrollPane.setBorder(BorderFactory.createTitledBorder("好友列表"));
        friendScrollPane.getVerticalScrollBar().setPreferredSize(new Dimension(10, Integer.MAX_VALUE));

        // 布局组装
        leftPanel.add(infoPanel, BorderLayout.NORTH);
        leftPanel.add(buttonPanel, BorderLayout.CENTER);
        leftPanel.add(listCardPanel, BorderLayout.SOUTH); // 使用卡片布局的面板

        mainSplitPane.setLeftComponent(leftPanel); // 把新面板加入主分割面板

        // 右侧面板 - 聊天界面
        chatArea = new JTextArea();
        chatArea.setEditable(false);
        chatArea.setLineWrap(true);
        chatArea.setWrapStyleWord(true);
        JScrollPane chatScrollPane = new JScrollPane(chatArea);

        // 输入区域
        JPanel inputPanel = new JPanel(new BorderLayout());
        inputField = new JTextField();
        JButton sendButton = new JButton("发送");

        // 发送消息动作
        sendButton.addActionListener(new SendAction());
        inputPanel.add(inputField, BorderLayout.CENTER);
        inputPanel.add(sendButton, BorderLayout.EAST);

        // 整合聊天界面
        JPanel rightPanel = new JPanel(new BorderLayout());
        rightPanel.add(chatScrollPane, BorderLayout.CENTER);
        rightPanel.add(inputPanel, BorderLayout.SOUTH);

        mainSplitPane.setRightComponent(rightPanel);

        // 添加到窗口
        add(mainSplitPane);
    }

    private int getGroupIdByName(String groupName) {
        try (SqlSession session = DbUtil.getSession()) {
            GroupMapper groupMapper = session.getMapper(GroupMapper.class);
            Group group = groupMapper.getGroupByName(groupName);
            return group != null ? group.getGroupId() : -1;
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        }
    }

    private void loadGroupChatHistory(String groupName) {
        try (SqlSession session = DbUtil.getSession()) {
            GroupMapper groupMapper = session.getMapper(GroupMapper.class);
            Group group = groupMapper.getGroupByName(groupName);

            if (group != null) {
                int groupId = group.getGroupId();
                GroupMessageMapper groupMessageMapper = session.getMapper(GroupMessageMapper.class);
                List<GroupMessage> groupMessages = groupMessageMapper.getGroupMessages(groupId);

                chatArea.setText("");
                for (GroupMessage msg : groupMessages) {
                    UserInfo sender = getUserInfoById(msg.getSenderId());
                    chatArea.append(sender.getAccountname() + ": " + msg.getContent() + "\n");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private UserInfo getUserInfoById(int userId) {
        try (SqlSession session = DbUtil.getSession()) {
            UserMapper userMapper = session.getMapper(UserMapper.class);
            return userMapper.getUserById(userId);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    //该方法用于从数据库加载群聊列表并更新 UI
    private void loadGroupsFromDatabase() {
        try (SqlSession session = DbUtil.getSession()) {
            // 假设有一个 GroupMapper 来处理群聊相关的操作
            GroupMapper groupMapper = session.getMapper(GroupMapper.class);
            List<Group> groups = groupMapper.getAllGroups();
            System.out.println("群聊列表：" +  groups);

            // 更新 JList
            groupListModel.clear();
            for (Group group : groups) {
                groupListModel.addElement(group.getGroupName());
            }
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, "加载群聊列表失败：" + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            e.printStackTrace();
        }
    }

    public void updateUserInfoDisplay(String newName, String newSign) {
        // 更新界面上的个人信息展示
        nameLabel.setText("昵称: " + newName);
        signLabel.setText("个性标签: " + newSign);
        userInfo.setUsername(newName);
        userInfo.setPersonSign(newSign);
    }


    // 发送按钮事件
    private class SendAction implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            String message = inputField.getText().trim();
            if (!message.isEmpty()) {
                if (currentFriendUserId != 0) {
                    // 发送私聊消息
                    try (SqlSession session = DbUtil.getSession()) {
                        Message msg = new Message();
                        msg.setSenderId(userInfo.getUserId());
                        msg.setReceiverId(currentFriendUserId);
                        msg.setContent(message);
                        MessageMapper messageMapper = session.getMapper(MessageMapper.class);
                        messageMapper.addMessage(msg);
                        session.commit();
                    }

                    out.println(currentFriendUserId + ":" + message);
                    chatArea.append("我: " + message + "\n");
                    inputField.setText("");
                } else if (currentGroupId != 0) {
                    // 发送群聊消息
                    try (SqlSession session = DbUtil.getSession()) {
                        GroupMessage msg = new GroupMessage();
                        msg.setSenderId(userInfo.getUserId());
                        msg.setGroupId(currentGroupId);
                        msg.setContent(message);
                        GroupMessageMapper groupMessageMapper = session.getMapper(GroupMessageMapper.class);
                        groupMessageMapper.addGroupMessage(msg);
                        session.commit();
                    }
                    out.println("group:" + currentGroupId + ":" + message);
                    chatArea.append("我: " + message + "\n");
                    inputField.setText("");
                } else {
                    JOptionPane.showMessageDialog(ChatFrame.this, "请先选择一个好友或群聊！", "提示", JOptionPane.WARNING_MESSAGE);
                }
            }
        }
    }
    //  网络通信
    private void connectToChatServer() {
        try {
            chatSocket = new Socket("localhost", 9000);
            out = new PrintWriter(chatSocket.getOutputStream(), true);
            in = new BufferedReader(new InputStreamReader(chatSocket.getInputStream()));

            // 发送自己的用户ID给服务器
            out.println(userInfo.getUserId());
            // 启动监听线程接收消息
            new Thread(this::listenForMessages).start();

        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, "无法连接到聊天服务器！", "错误", JOptionPane.ERROR_MESSAGE);
            e.printStackTrace();
        }
    }

    private void listenForMessages() {
        try {
            String line;
            while ((line = in.readLine()) != null) {
                if (line.startsWith("group:")) {
                    // 处理群聊消息
                    String[] parts = line.substring("group:".length()).split(":", 2);
                    int groupId = Integer.parseInt(parts[0]);
                    String message = parts[1];

                    if (groupId == currentGroupId) {
                        SwingUtilities.invokeLater(() -> {
                            chatArea.append(getGroupName(groupId) + ": " + message + "\n");
                        });
                    }
                } else {
                    // 处理私聊消息
                    String[] parts = line.split(":", 2);
                    int fromUserId = Integer.parseInt(parts[0]);
                    String message = parts[1];

                    if (fromUserId == currentFriendUserId) {
                        SwingUtilities.invokeLater(() -> {
                            chatArea.append(currentFriendUserInfo.getAccountname() + ": " + message + "\n");
                        });
                    }
                }
            }
        } catch (IOException e) {
            JOptionPane.showMessageDialog(this, "与服务器断开连接！", "错误", JOptionPane.ERROR_MESSAGE);
        }
    }
    private String getGroupName(int groupId) {
        try (SqlSession session = DbUtil.getSession()) {
            GroupMapper groupMapper = session.getMapper(GroupMapper.class);
            Group group = groupMapper.getGroupById(groupId);
            return group != null ? group.getGroupName() : "未知群聊";
        } catch (Exception e) {
            e.printStackTrace();
            return "未知群聊";
        }
    }

//加载历史记录的方法
private void loadChatHistory(int friendId) {
    System.out.println(friendId);
    try (SqlSession session = DbUtil.getSession()) {
        MessageMapper messageMapper = session.getMapper(MessageMapper.class);
        System.out.println("当前用户ID  ：  "+userInfo.getUserId()+ "和好友id"+friendId);
        List<Message> messages = messageMapper.getMessagesBetweenUsers(userInfo.getUserId(), friendId);
        chatArea.setText("");
        for (Message msg : messages) {
            String sender = msg.getSenderId() == userInfo.getUserId() ? "我" : currentFriendUserInfo.getAccountname();
            chatArea.append(sender + ": " + msg.getContent() + "\n");
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
// 消息
    public void showChat() {
        setVisible(true);
    }

}
